import SockJS from 'sockjs-client';
import { Client } from '@stomp/stompjs';

// WebSocket 单例管理
let stompClient = null;

export const connectWebSocket = (onMessageReceived) => {
  if (stompClient?.active) return;

  const socket = new SockJS('/ws'); // 注意这里使用相对路径
  stompClient = new Client({
    webSocketFactory: () => socket,
    reconnectDelay: 5000,
    debug: (str) => console.debug('STOMP:', str),
    onConnect: () => {
      console.log('WebSocket 已连接');
      stompClient.subscribe('/topic/auditQueue', (message) => {
        try {
          console.log('收到消息:', message.body);
          const msgData = JSON.parse(message.body);
          onMessageReceived(msgData);
        } catch (error) {
          console.error('消息解析失败:', error);
        }
      });
    },
    onStompError: (frame) => {
      console.error('协议错误:', frame.headers.message);
    }
  });

  stompClient.activate();
};

export const disconnectWebSocket = () => {
  console.log('WebSocket 已断开');
  if (stompClient) {
    stompClient.deactivate();
    stompClient = null;
  }
};